/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: GPT4Service.java</p>
 *
 * @author zz
 * @date 2024/4/7
 * @version 1.0
 * History:
 * v1.0.0 2024/4/7 Create
 */
package com.haohan.mess.service;

/**
 * <p>Title: GPT4Service</p>
 * <p>Description: </p>
 *
 * @author zz
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haohan.mess.entity.ChatReq;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.*;
import java.util.List;

@Service
public class GPT4Service {

    private final OkHttpClient okHttpClient;

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    @Autowired
    public GPT4Service(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    // 获取一个忽略所有 HTTPS 安全检查的 OkHttpClient 实例
    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // 安装信任所有证书的 trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // 创建一个 ssl socket factory 用于 OkHttp
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // 构建 OkHttpClient 并设置 SSL socket factory 和主机名验证器
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 创建一个信任所有证书的 X509TrustManager
    private final static TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            }
    };


    public Call createCall(String token, int n, List<ChatReq.Message> messages) throws Exception {
        // 创建 JSON 对象
        JSONArray jsonMessages = new JSONArray();
        for (ChatReq.Message message : messages) {
            JSONObject jsonMessage = new JSONObject();
            jsonMessage.put("role", message.getRole());
            jsonMessage.put("content", message.getContent());
            jsonMessages.add(jsonMessage);
        }

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "gpt-4");
        requestBody.put("stream",true);
        requestBody.put("token", token);
        requestBody.put("messages", jsonMessages);
        requestBody.put("params", new JSONObject().put("n", n));

        // 创建请求体
        RequestBody body = RequestBody.create(requestBody.toString(), JSON);
        Request request = new Request.Builder()
                .url("https://api.xiaoyukefu.com/v1/chat/completions")
                // 将token参数加入请求头
                .header("Authorization", "Bearer " + token)
                .post(body)
                .build();
        OkHttpClient okHttpClient = getUnsafeOkHttpClient();
        return okHttpClient.newCall(request);
    }
}

